package com.xiaojie.learn.util;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Http工具类，发送Http请求， Get请求请将参数放在url中 Post请求请将参数放在Map中,
 * 过期，请使用restTemplate
 */
@Deprecated
public class HttpUtil {
    private static final Logger log = LoggerFactory.getLogger(HttpUtil.class);
    private static final CloseableHttpClient HTTP_CLIENT = HttpClients.createDefault();
    private static final String USER_AGENT = "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.87 Safari/537.36";

    /**
     * 发送HttpGet请求
     *
     * @param url 求地址
     * @return 返回字符串
     */
    public static String sendGetStr(String url) {
        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader("User-Agent", USER_AGENT);

        String result = httpExecute(httpGet);

        return result;
    }

    /**
     * @param url
     * @return
     * @throws Exception
     */
    public static String sedPutStr(String url) {
        HttpPut httpput = new HttpPut(url);

        String result = httpExecute(httpput);

        return result;
    }

    /**
     * 发送不带参数的HttpPost请求 * * @param url * @return
     */
    public static String sendPost(String url) {
        // 得到一个HttpPost对象
        HttpPost httpPost = new HttpPost(url);
        // 防止被当成攻击添加的
        httpPost.setHeader("User-Agent", USER_AGENT);

        String result = httpExecute(httpPost);

        return result;
    }

    /**
     * 发送HttpPost请求
     *
     * @param url     请求地址
     * @param jsonStr 请求字符串
     * @return
     */
    public static String sendPostJson(String url, String jsonStr) {
        // 字符串编码
        StringEntity entity = new StringEntity(jsonStr, Consts.UTF_8);
        // 设置content-type
        entity.setContentType("application/json");
        HttpPost httpPost = new HttpPost(url);
        // 防止被当成攻击添加的
        httpPost.setHeader("User-Agent", USER_AGENT);
        // 接收参数设置
        httpPost.setHeader("Accept", "application/json");

        httpPost.setEntity(entity);

        String result = httpExecute(httpPost);

        return result;
    }

    /**
     * 发送HttpPost请求
     *
     * @param url 请求地址
     * @param map 请求参数
     * @return 返回字符串
     */
    public static String sendPostForm(String url, Map<String, String> map) {
        // 设置参数
        List<NameValuePair> formParams = new ArrayList<NameValuePair>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        // 编码
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formParams, Consts.UTF_8);
        // 取得HttpPost对象
        HttpPost httpPost = new HttpPost(url);
        // 防止被当成攻击添加的
        httpPost.setHeader("User-Agent", USER_AGENT);
        // 参数放入Entity
        httpPost.setEntity(formEntity);

        String result = httpExecute(httpPost);

        return result;
    }

    /**
     * 发送http请求，获取返回信息
     *
     * @param requestBase request请求（post，get，put，delete……）
     * @return
     */
    private static String httpExecute(HttpRequestBase requestBase) {
        String result = null;
        CloseableHttpResponse response = null;
        try {
            response = HTTP_CLIENT.execute(requestBase);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity, "UTF-8");
        } catch (IOException e) {
            log.error(e.getMessage());
        } finally {
            // 关闭CloseableHttpResponse
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
            }
        }
        return result;
    }
}